//
//  DiaryDetailMediaView.swift
//  MyDiary2025
//
//  Created by rolodestar on 2025/6/26.
//

import SwiftUI
import AVKit
import AVFoundation

struct DiaryDetailMediaView: View {
    var diary: DiaryModel
    let paddingSize : CGFloat = 30
    @State var isShowItem: Bool = false
    @State var selectedImageIndex: Int = 0
    @State var images:[Image] = []
    @State var videos:[Image] = []
    @State var fullScreenScrollPosition: ScrollPosition = ScrollPosition()
    private func calSize(size: CGFloat) -> CGFloat{
        return (size - paddingSize) / 3
    }
    
    func generateThumbnail(from url: URL) async  -> UIImage? {
        // 1. 准备媒体资源
        let asset = AVURLAsset(url: url, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])
        let generator = AVAssetImageGenerator(asset: asset)
        
        // 2. 配置生成参数
        generator.appliesPreferredTrackTransform = true  // 自动修正视频方向[1,3](@ref)
        generator.maximumSize = CGSize(width: 800, height: 600)  // 控制内存占用[6](@ref)
        generator.requestedTimeToleranceAfter = .zero  // 提高时间精度[3](@ref)
        generator.requestedTimeToleranceBefore = .zero
        
        // 3. 异步生成缩略图
        let time = CMTime(seconds: 1.0, preferredTimescale: 600)  // 高精度时间点[6](@ref)
        
        do {
            let cgImage = try await generator.image(at: time).image
            return UIImage(cgImage: cgImage)
        } catch {
            // 4. 错误处理
            print(error)
            //            throw ThumbnailError.generationFailed(
            //                reason: error.localizedDescription,
            //                code: (error as NSError).code
            //            )
            return nil
        }
    }
    
    // 错误类型封装
    enum ThumbnailError: Error, LocalizedError {
        case generationFailed(reason: String, code: Int)
        
        var errorDescription: String? {
            switch self {
            case .generationFailed(let reason, let code):
                return "缩略图生成失败(Error \(code)): \(reason)"
            }
        }
    }
    var body: some View {
       
            VStack{
                GeometryReader{reader in
                    if images.count + videos.count == 1{
                        EmptyView()
                    }else if images.count + videos.count == 1{
                        if images.count  == 1{
                            images[0]
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: reader.size.width - paddingSize,height: reader.size.width - paddingSize)
                            
                        }else if videos.count == 1{
                            ZStack(alignment: .center) {
                                videos[0]
                                    .resizable()
                                    .frame(width: calSize(size: reader.size.width),height: calSize(size: reader.size.width))
                                    .aspectRatio(contentMode: .fill)
                                Image(systemName: "play")
                                    .frame(width: 20, height: 20)
                            }
                        }
                        
                    }else{
                        LazyVGrid(columns: [GridItem(.fixed(calSize(size: reader.size.width))),GridItem(.fixed(calSize(size: reader.size.width))),GridItem(.fixed(calSize(size: reader.size.width)))]) {
                            ForEach(images){ img in
                                ZStack{
                                    img
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                        .frame(width: calSize(size: reader.size.width),height: calSize(size: reader.size.width))
                                        .clipped()
                                        .onTapGesture {
                                            let index = images.firstIndex(of: img) ?? 0
                                            self.selectedImageIndex = index
                                            print("selected \(index)")
                                            isShowItem = true
                                        }
                                    //                                Text("\(images.firstIndex(of: img)!)")
                                    //                                    .font(.title)
                                }
                            }
                            ForEach(videos){ video in
                                ZStack(alignment: .center) {
                                    video
                                        .resizable()
                                        .frame(width: calSize(size: reader.size.width),height: calSize(size: reader.size.width))
                                        .aspectRatio(contentMode: .fill)
                                    Image(systemName: "play.fill")
                                        .frame(width: 50, height: 50)
                                        .foregroundStyle(.white.opacity(0.5))
                                }
                                
                                //                            VideoPlayer(player: video)
                                //                                .frame(width: calSize(size: reader.size.width),height: calSize(size: reader.size.width))
                                //                                .aspectRatio(contentMode: .fill)
                            }
                            
                        }
                    }
                
            }
        }
           
        .fullScreenCover(isPresented: $isShowItem, content: {
            ZStack(alignment:.center){
                
                VStack{
                    
                }.background(.black)
                ScrollViewReader { proxy in
                    ScrollView(.horizontal){
                        LazyHStack(spacing: 0) {
                            ForEach(images){img in
                                ZStack{
                                    img
                                        .resizable()
                                        .aspectRatio(contentMode: .fit)
                                        .frame(width: UIScreen.main.bounds.width,height: UIScreen.main.bounds.height)
                                        .id(images.firstIndex(of: img)!)
                                        .onTapGesture {
                                            self.isShowItem = false
                                        }
//                                    Text("\(images.firstIndex(of: img)!)")
                                }
                            }
                        }.scrollTargetLayout()
                            .onAppear {
//                                proxy.scrollTo(selectedImageIndex)
//                                Task{@MainActor in
//                                   
//                                    try await Task.sleep(nanoseconds: 1_000_000_000)
//                                   
//                                    
//                                        print ("scroll to\(self.selectedImageIndex)")
//                                        fullScreenScrollPosition.scrollTo(id:  self.selectedImageIndex)
//                                    
//                                }
                            }
                    }
                    .scrollPosition($fullScreenScrollPosition)
                    .scrollTargetBehavior(.paging)
                    .scrollIndicators(ScrollIndicatorVisibility.visible)
                    .ignoresSafeArea()
                    .background(.black)
                    
                }
                
            }
        })
        .onAppear{
            let images = diary.images
            let videos = diary.videos
            Task.detached {
                
                for img in  images{
                    if let uiImage = UIImage(data: img){
                        await MainActor.run{
                            self.images.append(Image(uiImage: uiImage))
                        }
                    }
                }
                let folder = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
                for vid in videos{
                    do{
                        let fileName = "\(UUID().uuidString).mp4"
                        let filePath = folder.appending(path: fileName)
                        try vid.write(to: filePath)
                        if let thumb = await generateThumbnail(from: filePath)
                        {
                            await MainActor.run{
                                
                                self.videos.append(Image(uiImage: thumb))
                            }
                        }else{
                            await MainActor.run{
                                self.videos.append(Image(systemName: "video.circle"))
                            }
                        }
                        //                        let avPlayer = AVPlayer(url: filePath)
                        //                        avPlayer.pause()
                        
                    }catch{
                        print(error)
                    }
                }
            }
        }
    }
}

#Preview {
    DiaryDetailMediaView(diary: DiaryModel.debugData)
}
